//
//  SIComposeTextView.swift
//  SinaImiate
//
//  Created by xiaoming on 16/7/12.
//  Copyright © 2016年 GoodJob. All rights reserved.
//

import UIKit

/// 微博文本视图
class SIComposeTextView: UITextView {

    private lazy var placeholderLabel = UILabel()
    
    var emoticonText: String {
        
        guard let attrStr = attributedText else {
            
            return ""
            
        }
        
        var result = String()
        
        attrStr.enumerateAttributes(in: NSRange(location: 0, length: attrStr.length), options: []) { (dict, range, _) in
            if let attachment = dict["NSAttachment"] as? SIEmoticonAttachment {
                
                result += attachment.chs ?? ""
            } else {
                
                let subStr = (attrStr.string as NSString).substring(with: range)
                
                result += subStr
            }
        }
        return result
    }
    
    override func awakeFromNib() {
        setupUI()
    }
    
    //MARK: -监听方法
    @objc private func textChanged() {
        
        placeholderLabel.isHidden = self.hasText()
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }

}

extension SIComposeTextView {
    
    func insertEmoticon(em: SIEmoticon?) {
        
        guard let em = em else {
            
            deleteBackward()
            
            return
        }
        
        if let emoji = em.emoji, textRange = selectedTextRange {
            
            replace(textRange, withText: emoji)
            
            return
        }
        
        let imageText = em.imageText(font: font!)
        
        let attrStrm = NSMutableAttributedString(attributedString: attributedText)
        
        attrStrm.replaceCharacters(in: selectedRange, with: imageText)
        
        let range = selectedRange
        
        attributedText = attrStrm
        
        selectedRange = NSRange(location: range.location + 1, length: 0)
        
        delegate?.textViewDidChange?(self)
        
        textChanged()
    }
    
}


private extension SIComposeTextView {
    
    func setupUI() {
        
        NotificationCenter.default.addObserver(self, selector: #selector(textChanged), name: NSNotification.Name.UITextViewTextDidChange, object: self)
        
        placeholderLabel.text = "分享新鲜事..."
        placeholderLabel.font = self.font
        placeholderLabel.textColor = UIColor.lightGray()
        placeholderLabel.frame.origin = CGPoint(x: 5, y: 8)
        
        placeholderLabel.sizeToFit()
        
        addSubview(placeholderLabel)
        
    }
}
